package com.ojoin.trade.common_core.web.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.web.domain.IDentifiable;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;

/**
 * 版本校验工具类
 * @author guoting
 */
@Service
public class DataVersionValidationService {

	@Autowired
	private MerchantUserBaseService userservice;
	
	public void validateVO(int id, String tablename, Date clientTs) throws BusinessException {
		try {
			if(CommonUtils.isEmpty(clientTs))
				throw new BusinessException("传入待校验的ts值为空，请检查.");
			
			// 从数据库中读取vo数据的Ts
			String dbTs = userservice.selectTsByID(id, tablename);
			if (CommonUtils.isEmpty(dbTs)) 
				throw new BusinessException("tablename->" + tablename + ",id->" + id +"，该数据表中最后修改时间为空，数据错误.");
			
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date dbTsDate = df.parse(dbTs);
			if (clientTs.compareTo(dbTsDate) != 0) {
				throw new BusinessException(getErrorInfo());
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	
	public void validateVO(int id, String tablename, String clientTs) throws BusinessException {
		try {
			if(CommonUtils.isEmpty(clientTs))
				throw new BusinessException("传入待校验的ts值为空，请检查.");
			
			// 从数据库中读取vo数据的Ts
			String dbTs = userservice.selectTsByID(id, tablename);
			if (CommonUtils.isEmpty(dbTs)) 
				throw new BusinessException("tablename->" + tablename + ",id->" + id +"，该数据表中最后修改时间为空，数据错误.");
			
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date dbTsDate = df.parse(dbTs);
			Date clientTsDate = df.parse(clientTs);
			
			if (clientTsDate.compareTo(dbTsDate) != 0) {
				throw new BusinessException(getErrorInfo());
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	
	public void validateVO(IDentifiable vo, Date clientTs) throws BusinessException {
		validateVO(vo.getId(), vo.getTableName(), clientTs);
    }

	public void validateVO(IDentifiable vo, String clientTs) throws BusinessException {
		validateVO(vo.getId(), vo.getTableName(), clientTs);
    }
	
    public String getErrorInfo() {
        return "该数据已经被他人修改或删除，请刷新界面 ";
    }
}
